// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//


#include <fmt/core.h>
#include <gtest/gtest.h>
#include <algorithm>

#include <melon/conv.h>
#include <melon/optional.h>

#include <pollux/buffer/buffer.h>
#include <pollux/vector/vector_util.h>

namespace kumo::pollux::test {

template <typename T>
class VectorUtilTest : public testing::Test {
 public:
  void runTest(melon::Optional<int32_t> size = melon::none) {
    std::vector<T> vec;
    constexpr int32_t kSize = 3;
    for (size_t i = 1; i <= kSize; ++i) {
      vec.emplace_back(melon::to<T>(i));
    }
    auto buffer = copyToBuffer(vec, pool_.get(), size);
    int32_t actualBufferSize =
        size.hasValue() ? std::min(size.value(), kSize) : kSize;
    ASSERT_EQ(actualBufferSize * sizeof(T), buffer->size());
  }

  void runTestWithEmptyVector() {
    std::vector<T> vec;
    auto buffer = copyToBuffer(vec, pool_.get());
    ASSERT_EQ(0, buffer->size());
  }

  void runTestWithEmptyVectorAndReturnsNullptr() {
    std::vector<T> vec;
    auto buffer = copyToBuffer(
        vec, pool_.get(), melon::none /*size*/, true /*returnsNullptr*/);
    ASSERT_EQ(nullptr, buffer);
  }

 protected:
  void SetUp() override {
    pool_ = memoryManager_.addLeafPool("VectorUtilTest");
  }

  memory::MemoryManager memoryManager_;
  std::shared_ptr<memory::MemoryPool> pool_;
};

using ScalarTypes =
    ::testing::Types<int8_t, int16_t, int32_t, int64_t, double, char>;

TYPED_TEST_CASE(VectorUtilTest, ScalarTypes);

TYPED_TEST(VectorUtilTest, copyToBuffer) {
  this->runTest();
}

TYPED_TEST(VectorUtilTest, copyToBufferWithSpecifiedSize) {
  this->runTest(1 /*size*/);
}

TYPED_TEST(VectorUtilTest, copyToBufferWithEmptyVector) {
  this->runTestWithEmptyVector();
}

TYPED_TEST(VectorUtilTest, copyToBufferWithEmptyVectorReturnsNullptr) {
  this->runTestWithEmptyVectorAndReturnsNullptr();
}

} // namespace kumo::pollux::test
